﻿using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using WLMCoreLibrary;
using MiWebSite_Core;
using Newtonsoft.Json;

namespace MWS_Blog.Edit
{
    public partial class Edit : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["guardar"] != null)
                GuardarRegistro();
            if(Request.QueryString["idPost"]!=null)
            {
                CargarRegistro(Convert.ToInt32(Request.QueryString["idPost"]));
            }
        }

        protected void CargarRegistro(int idReg)
        {
            WebSiteMainConfiguration config = WebSiteMainConfiguration.GetConfig();
            dbConnector ConexionDB = new dbConnector(config.Connections[0].value);
            MiWebSiteBlogEntry entry= new MiWebSiteBlogEntry(idReg, ref ConexionDB);
            idPostActual.Value = entry.id.ToString();
            TituloPost.Text = entry.titulo;
            EditorBlogContenido.Text = entry.contenido;
            EditorBlogContenidoExtra.Text = entry.contenidoExtra;
            listaCats.SelectionMode = ListSelectionMode.Multiple;
            foreach (MiWebSiteBlogCategoria categoria in entry.Categorias)
                listaCats.Items.Add(new ListItem(categoria.NombreCategoria, categoria.id.ToString()));
            foreach (MiWebSiteBlogTag tag in entry.Tags)
                listaTags.Items.Add(new ListItem(tag.NombreTag, tag.id.ToString()));
            idGaleriaPostNuevo.Value = entry.idGaleria.ToString();
            if (entry.idGeoTag != 0)
            {
                MapaLatitud.Value = entry.geoTag.Latitud.ToString();
                MapaLongitud.Value = entry.geoTag.Longitud.ToString();
            }
            ConexionDB.CloseConnection();
        }

        protected void GuardarRegistro()
        {
            Response.Clear();
            Response.ContentType = "text/xml";
            Response.ContentEncoding = System.Text.Encoding.UTF8;
            if (CurrentUser.IdUsuario != 0)
            {
                WebSiteMainConfiguration config = WebSiteMainConfiguration.GetConfig();
                dbConnector ConexionDB = new dbConnector(config.Connections[0].value);
                try
                {
                    bool newEntryIndicator = false;
                    string nombreEntry = Request["urlEntryEdit"];
                    if (nombreEntry == null)
                        nombreEntry = MiWebSiteFunctions.tituloaPostName(TituloPost.Text);
                    string tituloEntry = TituloPost.Text;
                    string contenido = Request["EditorBlogContenido"];
                    string contenidoExtra = Request["EditorBlogContenidoExtra"];
                    MiWebSiteBlogEntry blogEntry = new MiWebSiteBlogEntry(Convert.ToInt32(idPostActual.Value), ref ConexionDB);
                    if (blogEntry.id == 0)
                    {
                        blogEntry = new MiWebSiteBlogEntry(ref ConexionDB);
                        blogEntry.PostName = MiWebSiteFunctions.cleanContentName(nombreEntry);
                        newEntryIndicator = true;
                    }
                    if (tituloEntry != blogEntry.titulo)
                    {
                        blogEntry.titulo = tituloEntry;
                        blogEntry.PostName = MiWebSiteFunctions.tituloaPostName(tituloEntry);
                    }
                    blogEntry.contenido = contenido;
                    blogEntry.contenidoExtra = contenidoExtra;
                    blogEntry.ListaCategorias = Server.UrlDecode(Request["listaCats[]"]);
                    blogEntry.ListaTags = Server.UrlDecode(Request["listaTags[]"]);
                    blogEntry.idGaleria =Convert.ToInt32( idGaleriaPostNuevo.Value);
                    if (MapaLatitud.Value != "0")
                    {
                        if (blogEntry.idGeoTag == 0)
                        {
                            blogEntry.geoTag = new GeoTag(ref ConexionDB);
                            blogEntry.idGeoTag = blogEntry.geoTag.id;
                        }

                        blogEntry.geoTag.Latitud = Convert.ToDouble(MapaLatitud.Value);
                        blogEntry.geoTag.Longitud = Convert.ToDouble(MapaLongitud.Value);
                        blogEntry.geoTag.Save();
                    }

                    blogEntry.Save(true);
                    if(twitearPostActual.Value=="1")
                    try
                    {
                        if (CurrentDomain.oauth_token != "")
                        {
                            Twitter tw = new Twitter();
                            string shorURL = Bitly.Shortener(blogEntry.URLEntry);
                            tw.Update(shorURL + " - " + blogEntry.titulo);
                        }
                    }
                    catch { }
                    Response.Write(WLMFunctions.SerializeObject(new SuccessObject(newEntryIndicator ? SuccessCode.RegistrySaved : SuccessCode.RegistryUpdated, "", WLMFunctions.SerializeObject(blogEntry)), true));
                }
                catch (Exception ex)
                {
                    Response.Write(WLMFunctions.SerializeObject(new ErrorObject(ErrorCode.CompilationError, "", ex.Message, ex.StackTrace), true));
                }
                ConexionDB.CloseConnection();
            }
            else
            {
                Response.Write(WLMFunctions.SerializeObject(new ErrorObject(ErrorCode.UserNotLogged), true));
            }
            Response.End();
        }
    }
}